import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SearchLogic extends GetxController {
  String cacheKey = 'home_search';
  List<String> list = [];

  @override
  void onInit() {
    super.onInit();
    getHistory();
  }

  getHistory() {
    SharedPreferences.getInstance().then((SharedPreferences value) {
      list = value.getStringList(cacheKey) ?? [];
      update();
    });
  }

  clearHistory() {
    SharedPreferences.getInstance().then((value) {
      value.remove(cacheKey);
      list = [];
      update();
      MyToast.show('清除历史记录成功');
    });
  }

  // 保存数据到本地缓存
  saveHistory(String key) async {
    SharedPreferences.getInstance().then((value) {
      List<String> keys = value.getStringList(cacheKey) ?? [];
      if (keys.length > 20) {
        keys.removeLast();
      }
      keys.insert(0, key);
      value.setStringList(cacheKey, keys);
      Get.back(result: key);
    });
  }
}
